import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { storeLogger } from '@/utils/logger'

export const useAlertsStore = defineStore('alerts', () => {
  // 状态
  const alerts = ref([])
  const loading = ref(false)
  const total = ref(0)           // 当前筛选条件下的总数（用于分页）
  const totalAll = ref(0)        // 全部数据的总数（用于统计卡片显示）
  const statusStats = ref({})    // 全部数据的状态统计（用于统计卡片显示）
  const currentPage = ref(1)
  const pageSize = ref(20)
  const stats = ref({})
  const trends = ref([])
  const hotspots = ref({})
  const selectedAlerts = ref([])
  
  // 搜索条件
  const searchForm = ref({
    job_name: '',
    alert_type: '',
    status: '',
    time_range: '',
    search: '',
    sort_by: 'sent_time',
    sort_order: 'DESC'
  })
  
  // 获取全部数据统计（无搜索条件）
  // 注意：现在后端在每次请求中都会返回全局统计，这个方法已不再需要单独调用
  const fetchAllStats = async () => {
    try {
      const response = await api.get('/alerts', { 
        params: { page: 1, size: 20 } // 只获取第一页即可，统计数据会一起返回
      })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      
      // 后端现在直接返回全局统计
      if (data.hasOwnProperty('total_all')) {
        totalAll.value = data.total_all
      }
      if (data.hasOwnProperty('status_stats')) {
        statusStats.value = data.status_stats
      }
      
      storeLogger.info('Alerts all stats fetched successfully', { 
        totalAll: totalAll.value,
        statusStats: statusStats.value
      })
    } catch (error) {
      storeLogger.error('Failed to fetch alerts all stats', error)
    }
  }
  
  // 获取告警列表
  const fetchAlerts = async (params = {}) => {
    try {
      loading.value = true
      const queryParams = {
        page: currentPage.value,
        size: pageSize.value,
        ...searchForm.value,
        ...params
      }
      
      // 清理空值
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })
      
      const response = await api.get('/alerts', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      alerts.value = data.rows || []
      // 确保使用后端返回的真实总数，即使为0也要使用
      total.value = data.hasOwnProperty('total') ? data.total : alerts.value.length
      
      // 后端现在直接返回全局统计数据（不管是否有筛选条件）
      if (data.hasOwnProperty('total_all')) {
        totalAll.value = data.total_all
      }
      if (data.hasOwnProperty('status_stats')) {
        statusStats.value = data.status_stats
      }
      
      return response.data
    } catch (error) {
      storeLogger.error('获取告警列表失败:', error)
      ElMessage.error('获取告警列表失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 重置搜索条件
  const resetSearch = () => {
    searchForm.value = {
      job_name: '',
      alert_type: '',
      status: '',
      time_range: '',
      search: '',
      sort_by: 'sent_time',
      sort_order: 'DESC'
    }
    currentPage.value = 1
  }

  // 获取告警详情
  const getAlertDetail = async (alertId) => {
    try {
      const response = await api.get(`/alerts/${alertId}`)
      return response.data
    } catch (error) {
      storeLogger.error('获取告警详情失败:', error)
      ElMessage.error('获取告警详情失败')
      throw error
    }
  }

  // 获取告警统计
  const fetchStats = async (timeRange = 'week', alertTypes = null) => {
    try {
      const params = { time_range: timeRange }
      if (alertTypes && alertTypes.length > 0) {
        params.alert_types = Array.isArray(alertTypes) ? alertTypes.join(',') : alertTypes
      }
      const response = await api.get('/alerts/stats', { params })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      stats.value = data
      return response.data
    } catch (error) {
      storeLogger.error('获取告警统计失败:', error)
      ElMessage.error('获取告警统计失败')
      throw error
    }
  }

  // 获取告警趋势
  const fetchTrends = async (period = 'daily', days = 7) => {
    try {
      const response = await api.get('/alerts/trends', {
        params: { period, days }
      })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      trends.value = data.trends || []
      return response.data
    } catch (error) {
      storeLogger.error('获取告警趋势失败:', error)
      ElMessage.error('获取告警趋势失败')
      throw error
    }
  }

  // 获取告警热点
  const fetchHotspots = async (days = 7, limit = 10, alertTypes = null) => {
    try {
      const params = { days, limit }
      if (alertTypes && alertTypes.length > 0) {
        params.alert_types = Array.isArray(alertTypes) ? alertTypes.join(',') : alertTypes
      }
      const response = await api.get('/alerts/hotspots', { params })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      hotspots.value = data
      return response.data
    } catch (error) {
      storeLogger.error('获取告警热点失败:', error)
      ElMessage.error('获取告警热点失败')
      throw error
    }
  }

  // 解决告警
  const resolveAlert = async (alertId, data = {}) => {
    try {
      const response = await api.post(`/alerts/${alertId}/resolve`, data)
      ElMessage.success('告警已解决')
      return response.data
    } catch (error) {
      storeLogger.error('解决告警失败:', error)
      ElMessage.error('解决告警失败')
      throw error
    }
  }

  // 静默告警
  const silenceAlert = async (alertId, data = {}) => {
    try {
      const response = await api.post(`/alerts/${alertId}/silence`, data)
      ElMessage.success(`告警已静默 ${data.minutes || 60} 分钟`)
      return response.data
    } catch (error) {
      storeLogger.error('静默告警失败:', error)
      ElMessage.error('静默告警失败')
      throw error
    }
  }

  // 升级告警
  const escalateAlert = async (alertId, data = {}) => {
    try {
      const response = await api.post(`/alerts/${alertId}/escalate`, data)
      ElMessage.success('告警已升级')
      return response.data
    } catch (error) {
      storeLogger.error('升级告警失败:', error)
      ElMessage.error('升级告警失败')
      throw error
    }
  }

  // 删除告警
  const deleteAlert = async (alertId) => {
    try {
      const response = await api.post(`/alerts/${alertId}/delete`)
      ElMessage.success('告警已删除')
      return response.data
    } catch (error) {
      storeLogger.error('删除告警失败:', error)
      ElMessage.error('删除告警失败')
      throw error
    }
  }

  // 批量操作告警
  const batchOperation = async (alertIds, action, data = {}) => {
    try {
      const response = await api.post('/alerts/batch', {
        alert_ids: alertIds,
        action,
        ...data
      })
      
      const { success, failed, total } = response.data
      if (success > 0) {
        ElMessage.success(`成功处理 ${success}/${total} 个告警`)
      }
      if (failed > 0) {
        ElMessage.warning(`${failed} 个告警处理失败`)
      }
      
      return response.data
    } catch (error) {
      storeLogger.error('批量操作失败:', error)
      ElMessage.error('批量操作失败')
      throw error
    }
  }

  // 获取恢复状态
  const getRecoveryStatus = async () => {
    try {
      const response = await api.get('/alerts/recovery-status')
      return response.data
    } catch (error) {
      storeLogger.error('获取恢复状态失败:', error)
      ElMessage.error('获取恢复状态失败')
      throw error
    }
  }

  // 获取告警指标
  const getMetrics = async (timeRange = '24h') => {
    try {
      const response = await api.get('/alerts/metrics', {
        params: { time_range: timeRange }
      })
      return response.data
    } catch (error) {
      storeLogger.error('获取告警指标失败:', error)
      ElMessage.error('获取告警指标失败')
      throw error
    }
  }

  // 生成报告
  const generateReport = async (type = 'summary', startDate, endDate, format = 'json') => {
    try {
      const response = await api.get('/alerts/reports', {
        params: {
          type,
          start_date: startDate,
          end_date: endDate,
          format
        }
      })
      return response.data
    } catch (error) {
      storeLogger.error('生成报告失败:', error)
      ElMessage.error('生成报告失败')
      throw error
    }
  }

  // 清空所有告警
  const clearAllAlerts = async () => {
    try {
      const response = await api.post('/alerts/clear-all')
      ElMessage.success('所有告警已清空')
      return response.data
    } catch (error) {
      storeLogger.error('清空告警失败:', error)
      ElMessage.error('清空告警失败')
      throw error
    }
  }
  
  const alertTypeCache = new Map()
  const getAlertTypeType = (alertType) => {
    if (alertTypeCache.has(alertType)) {
      return alertTypeCache.get(alertType)
    }
    const alertTypeMap = {
      'FIRST_FAILURE': 'danger',
      'RETRY_FAILURE': 'warning',
      'FINAL_FAILURE': 'danger',
      'RECOVERED': 'success',
      'FIRING': 'danger',
      'RESOLVED': 'success',
      'ALERTMANAGER': 'info',
      'OTHER': 'info'
    }
    const result = alertTypeMap[alertType] || 'info'
    alertTypeCache.set(alertType, result)
    return result
  }

  // 状态类型映射
  const getStatusType = (status) => {
    const statusMap = {
      'ACTIVE': 'warning',
      'RESOLVED': 'success',
      'ESCALATED': 'danger',
      'SILENCED': 'info',
      'FIRING': 'danger'
    }
    return statusMap[status] || 'info'
  }
  
  return {
    // 状态
    alerts,
    loading,
    total,
    totalAll,
    statusStats,
    currentPage,
    pageSize,
    searchForm,
    stats,
    trends,
    hotspots,
    selectedAlerts,
    
    // 方法
    fetchAlerts,
    fetchAllStats,
    resetSearch,
    getAlertDetail,
    fetchStats,
    fetchTrends,
    fetchHotspots,
    resolveAlert,
    silenceAlert,
    escalateAlert,
    deleteAlert,
    batchOperation,
    getRecoveryStatus,
    getMetrics,
    generateReport,
    clearAllAlerts,
    getAlertTypeType,
    getStatusType
  }
})
